package logic

import (
	"api/client"
	"api/request"
	"common/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	user "user_srv/proto"
)

func UserLogin(c *gin.Context) {
	var data request.UserLoginRequest
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	res, err := client.UserLogin(c, &user.UserLoginRequest{
		Tel:  data.Tel,
		Code: data.Code,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	token, err := pkg.NewJWT("2209ABC").CreateToken(pkg.CustomClaims{ID: uint(res.Userid)})
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登陆成功",
		"data": gin.H{
			"token": token,
		},
	})
}
